import os, pickle
from ..classes import *


class PickleStorage:
	def __init__(self, name):
		self.directory = "data/" + name
		try:
			self.load()
		except:
			self.clean()

	def load(self):
		if not os.path.exists(self.directory):
			os.makedirs(self.directory)
		with open(self.directory + '/lodger.db', 'rb') as f:
			(self.maxID, self.items) = pickle.load(f)

	def store(self):
		with open(self.directory + '/lodger.db', 'wb') as f:
			pickle.dump((self.maxID, self.items), f)

	def clean(self):
		self.items = {}
		self.maxID = 0

	def getItem(self, id):
		if id <= 0:
			return LodgerItem()
		else:
			print(id)
			if id in self.items:
				return self.items[id]
			return None

	def addItem(self, item):
		if item.id <= 0:
			self.maxID += 1;
			item.id = self.maxID
			self.items[item.id] = item

	def deleteItem(self, id):
		if id in self.items:
			del self.items[id]

	def getItems(self):
		for id, item in self.items.items():
			yield (item)
